<h3>Comments</h3>

<?php 
function render_comments_tree($comments, $us, $ro, $t) {
    $res = '';
    
    foreach ($comments as $c) {
        // skip not approved comments for regular users
        if (!$c['approved'] and !$us->hasCredential('comments.view_not_moderated')) {
            continue;
        }

        $name = htmlspecialchars($c['name']);
        if ($c['is_user']) {
            $img = '';
            if ($c['type'] === 'openid') {
                $img = '<img src="images/openid_icon.png" class="openid" />'; 
            }
            if ($c['website']) {
                $name = sprintf('<a href="%s" onclick="return false;">%s%s</a>', $c['website'], $img, $name);
            } else {
                $name = $img . $name;
            }
        } elseif ($c['is_owner']) {
            $name = '<b>'. $name .'</b>';
        } else {
            // anonymous user
            if ($c['website']) {
                $name = sprintf('<a href="%s" onclick="return false;">%s</a>', $c['website'], $name);
            }
        }
        $links = sprintf('<a href="" onclick="show_comment_form(\'#cid%s\', %d); return false;">reply to this comment</a>
        	<a href="%s#c%d">permalink</a>', $c['id'], $c['id'], $t['post_url'], $c['id']);
        
        if ($us->hasCredential('comments.moderator')) {
            $service_links = array();
            $service_links[] = sprintf('<a href="%s">[delete]</a>', $ro->gen('comment.delete', array('comment_id'=>$c['id'])));
            if (!$c['approved']) {
                $service_links[] = sprintf('<a href="%s">[approve]</a>',
                    $ro->gen('comment.approve', array('comment_id'=>$c['id'])));
            }
            
            $links .= ' ' . implode(' ', $service_links);
        }
        $title = sprintf('<span class="name">%s</span> <span class="time">%s</span> %s', $name, $c['time']->format('Y-m-d H:i'), $links);
        $comment = sprintf('<div class="title">%s</div>', $title);
        $comment .= sprintf('<div class="body" id="cid%d">%s</div>', $c['id'], MarkupProcessor::renderCommentText($c['text']));
        $subcomments = render_comments_tree($c['subcomments'], $us, $ro, $t);
        $comment_class = $c['approved'] ? 'comment-normal' : 'comment-hidden';
        $comment = sprintf('<div class="%s"><a name="c%s"/>%s<div class="comments">%s</div></div>',
            $comment_class, $c['id'], $comment, $subcomments);
        $res .= $comment;
    }
    
    return $res;
}
?>
<div class="comments">
<?php echo render_comments_tree($t['comments'], $us, $ro, $t); ?>
</div>
